import {
    toast,
    promptBox
} from 'nc-lightapp-front';
import {COMMON, getCheckedRows, toastMsg} from "../../../main/util";

export default class ButtonAction {
    constructor(comp) {
        this.comp = comp;
        this.dispatch = this.comp.props.dispatch;
    }

    // 初始化
    didMount = () => {
        let {props} = this.comp;
        let effectdate = getCheckedRows(props, 'effectdate');
        if (Array.isArray(effectdate) && effectdate.length === 1) {
            this.comp.setState({
                effectDate: effectdate[0]
            });
        }
    };

    /**
     * 执行
     * @param billids {Array<String>} []
     * @param effectDate {String} 20190202
     * @param pk_org
     * @returns {Promise<void>}
     */
    execute = async ({billids, effectDate, pk_org} = {}) => {
        let {props, state} = this.comp;
        let {transfer} = props;
        if(!billids){
            if (transfer.page === COMMON.pageMain) {
                billids = getCheckedRows(props, 'pk_hi_stapply');
            } else if (transfer.page === COMMON.pageDetail) {
                billids = transfer.billid;
            }
        }
        !effectDate && (effectDate = state.effectDate);
        !pk_org && (pk_org = transfer.hrorgobj.refpk);
        if (!this.checkEffectDate(effectDate)) return;
        let postData = {
            billids,
            effectDate,
            pk_org
        };
        try {
            let res = await this.dispatch({
                type: 'transfer/excuteAction',
                payload: {
                    postData
                }
            });
            if (!res.success) return;
            toastMsg(res, transfer);
            if (res.data.warning) return;

            toast({
                color: 'success',
                content: this.comp.props.transfer.language['gx6008-000112'] // 执行成功
            });
            if (transfer.page === COMMON.pageMain) {
                this.pubSub.publish('getMainTableData');
            } else if (transfer.page === COMMON.pageDetail) {
                this.comp.props.queryDetailData();
            }
            this.comp.props.onClose();
        } catch (e) {
            console.log(e)
        }
    };

    // 执行前检测
    checkEffectDate = (effectDate) => {
        if(!effectDate){
            toast({
                color: 'danger',
                content: this.comp.props.transfer.language['gx6008-000281'] // 请选择生效日期
            });
        }
        return !!effectDate
    };
    // 选择生效日期
    handelDateChange = (value) => {
        // const {props: {dispatch}, state} = this.comp;

        this.comp.setState({
            effectDate: value
        });
    };
}